<script setup lang="ts">
// 导入 BlogCard 组件
import BlogCard from '@/components/BlogCard.vue'

// 导入使用页面标题的自定义
import { usePageTitle } from '@/hooks/usePageTitle'

// 导入获取博客列表的 API
import { getBlogList as getBlogListApi } from '@/api/blog.ts'

// 导入 Vue Router 的相关函数
import { useRoute, useRouter } from 'vue-router'

// 导入 Vue 的相关函数
import { ref, watchEffect, watch } from 'vue'

// 修改页面标题
usePageTitle('首页')

// 定义数据
const list = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const route = useRoute()
const router = useRouter()

// 使用watchEffect 监听 url 参数 page size category keyword变化，并获取博客列表和总数
watchEffect(async () => {
  const page = ref(route.query.page || 1)
  const size = ref(route.query.size || 10)
  const category = ref(route.query.category || '')
  const keyword = ref(route.query.keyword || '')

  const queryInfo = {
    page,
    size,
    category,
    keyword
  }
  const res: any = await getBlogListApi(queryInfo)
  list.value = res.list
  total.value = res.total
})

// 定义处理当前页变化的函数
const handleCurrentChange = (newPage: number) => {
  router.push({
    query: {
      ...route.query,
      page: newPage
    }
  })

  currentPage.value = newPage
}

// 使用 watch 监听 currentPage 的变化，打印日志
watch(currentPage, (newPage) => {
  console.log('Current Page:', newPage)
})
</script>
<template>
  <div class="home">
    <main>
      <div class="blog-container">
        <BlogCard :blog="blog" v-for="blog in list" :key="blog" />
        <div class="pagination-container">
          <el-pagination
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </div>
    </main>
  </div>
</template>

<style lang="scss" scoped>
/* .blog-container {
} */

.pagination-container {
  display: flex;
  justify-content: center;
}
</style>
